package org.example.cloudapply.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.example.cloudapply.dto.TemplateCreateDTO;
import org.example.cloudapply.entity.CloudType;
import org.example.cloudapply.entity.InstanceTemplate;
import org.example.cloudapply.repository.TemplateRepository;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class TemplateService {
    private final TemplateRepository templateRepository;

    public List<InstanceTemplate> getTemplates(CloudType cloudType) {
        return templateRepository.findByCloudType(cloudType);
    }

    @Transactional
    public void createTemplate(TemplateCreateDTO dto) {
        InstanceTemplate template = new InstanceTemplate();
        template.setCloudType(dto.getCloudType());
        template.setCpuCores(dto.getCpuCores());
        template.setMemoryGb(dto.getMemoryGb());
        template.setGpuSupported(dto.getGpuSupported());

        templateRepository.insert(template);
    }
    public PageInfo<InstanceTemplate> getTemplatesAll( int page, int size) {
        PageHelper.startPage(page, size);
        List<InstanceTemplate> list = templateRepository.findAll();
        return new PageInfo<>(list);
    }
    // TemplateService.java
    public PageInfo<InstanceTemplate> getTemplatesByPage(CloudType cloudType, int page, int size) {
        PageHelper.startPage(page, size);
        List<InstanceTemplate> list = templateRepository.findByCloudType(cloudType);
        return new PageInfo<>(list);
    }
    public void deleteTemplate(Integer templateId) {
        int affected = templateRepository.deleteById(templateId);
        if (affected == 0) {
            throw new RuntimeException("模板不存在或已被删除");
        }
    }
}